package de.tempel.pong.util;

import java.awt.geom.Point2D;

public class Rectangle2D extends java.awt.geom.Rectangle2D.Double {

	private static final long serialVersionUID = 1L;

	public Rectangle2D(double x, double y, double width, double heigth) {
		super(x, y, width, heigth);
	}

	/**
	 * Berechnet Schnittpunkt zwischen einer Linie und einem Rechteckt. Wenn es
	 * mehrere gibt wird der am nächsten zum viewPoint liegende Schnittpunkt
	 * zurückgegeben.
	 * 
	 * @param line
	 * @param viewPoint
	 * @return
	 */
	public Point2D intersectionPoint(Line2D line, Point2D viewPoint) {

		double firstLineX = this.getX();
		double secondLineX = this.getX() + this.getWidth() - 1;

		Point2D intersectionPoint1 = new Point2D.Double(firstLineX,
				line.yForX(firstLineX));
		Point2D intersectionPoint2 = new Point2D.Double(secondLineX,
				line.yForX(secondLineX));

		boolean containsPoint1 = this.contains(intersectionPoint1);
		boolean containsPoint2 = this.contains(intersectionPoint2);

		if (containsPoint1 && !containsPoint2) {
			return intersectionPoint1;
		} else if (!containsPoint1 && containsPoint2) {
			return intersectionPoint2;
		} else if (containsPoint1 && containsPoint2) {

			// Berechne Distanz zum Kollisionspunkt
			double distance1 = viewPoint.distance(intersectionPoint1);
			double distance2 = viewPoint.distance(intersectionPoint2);

			if (distance1 < distance2) {
				return intersectionPoint1;
			} else {
				return intersectionPoint2;
			}
		}

		return null;
	}

}
